package com.FindMyStuff.Model;

import android.content.Context;

/**
 * Singleton that
 * Interfaces with the database to log in users
 * Keeps track of current user
 *
 */
public class SessionManager {
	/**
	 * current logged in user
	 */
	private User currentUser;
	/**
	 * Current instance of Session Manager
	 */
	private static SessionManager sm;
	public Item matchedItem;
	
	private SessionManager()
	{
		super();
	}
	
	/**
	 * A getter for currentUser
	 * @return currentUser
	 */
	public User getCurrentUser()
	{
		return currentUser;
	}
	
	/**
	 * Attempts to log in a user with the given email and password
	 * @param context
	 * @param email The User's email
	 * @param password The User's password
	 * @return The User if successful, null otherwise
	 */
	
	public User attemptLogIn(Context context, String email, String password)
	{
		DataBaseHelper dbh = new DataBaseHelper(context);
		DataAccessor da = new DataAccessor(dbh);
		User user = da.getUserByEmail(email);
		if(user.checkPassword(password))
		{
			LogIn(user);
			da.logInSuccess(user);
		} else
		{
			da.logInFailed(user);
		}
		return user;
	}
	
	/**
	 * Logs in a given user
	 * @param user A valid User
	 */
	public void LogIn(User user)
	{
		currentUser = user;
		user.logInSucess();
	}
	
	/**
	 * Logs the current user out.
	 */
	public void logout(){
		currentUser=null;
	}
	
	/**
	 * Returns the current instance of Session Manager or creates a new one if it doesn't exist
	 * @return SessionManager current instance of Session Manager
	 */
	public static SessionManager getInstance() {
		if(sm != null)
		{
			return sm;
		}
		sm = new SessionManager();
		return sm;
	}

}
